/**
 * 2017年3月9日
 */
package cn.edu.bjtu.alex.rewrite.components;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;

import cn.edu.bjtu.alex.rewrite.Context;
import cn.edu.bjtu.alex.rewrite.interfaces.Term;
import cn.edu.bjtu.alex.rewrite.interfaces.TermFeatureable;

/**
 * @author Alex
 *
 */
public class TransformOutputing extends SortSupport<Term> {
	Map<String,TermFeatureable> features = null;
	public TransformOutputing(Context ctx) {
		super(ctx);
	}
	@Override
	protected void fitInternal() {}

	@Override
	protected void transformInternal() {
		OutputStream os = ctx.getOs();
		if(os instanceof ByteArrayOutputStream){
			//清空线程中上次输出缓存
			ByteArrayOutputStream baos =(ByteArrayOutputStream)os;
			baos.reset();
		}
		PrintWriter pw = new PrintWriter(os);
		Map<String,Map<String, Term>> map = ctx.getTransformedDocument();
		features = ctx.featuredTermsMap();
		for(Entry<String,Map<String, Term>> entry:map.entrySet()){
			pw.println("Document ID:"+entry.getKey()+"<br>");
			Map<String, Term> m = entry.getValue();
			sortMap(m);
			while(hasNext()){
				Entry<String,Term> word = next();
				pw.print(String.format("wordid:%d,word:%s,tf:%f,idf:%f,tfidf:%f<br>",features.get(word.getKey()).getId(), word.getKey(),word.getValue().getTf(),features.get(word.getKey()).getMeasureValue(),word.getValue().getTfidf()));
			}
			
			pw.println("====================================<br>");
		}
		pw.flush();
		

	}

	@Override
	protected int sortBy(String key) {
		// TODO Auto-generated method stub
		return features.get(key).getId();
	}

	@Override
	protected boolean shouldAdd(Entry<String, Term> entry) {
		return features.containsKey(entry.getKey());
	}
	

}
